/**
 * Created by huotaol on 2017/9/30.
 */
import { Button, Cascader, DatePicker, Form, Input, message, Modal, Popconfirm, Select, Table } from "antd";
import React from "react";
import { connect } from "react-redux";
import { fetchData, receiveData, updateMember } from "@/action";
import request, { get } from "@/axios/tools";
import axios from "axios";

import { uuid } from "@/utils";

import moment from "moment";
import { bindActionCreators } from "redux";
import PayBill from "@/components/form/PayBill";
import AddFood from "@/components/form/AddFood";
import AddOrder from "@/components/form/AddOrder";
import ExpandTable from "@/components/tables/ExpandTable";

// import TextArea from "antd/lib/input/TextArea.d";

const { MonthPicker, RangePicker } = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;
const DEFAULT_PAGE_SIZE = 15;
const FORMAT_DATE = 'YYYY-MM-DD HH:mm';
const FOODS_ROW = 5;

const { TextArea } = Input;

// 取消菜品 样式
const disableText = {
    textDecoration: 'line-through',
    opacity: .6
}
const typeMap = {
    'CASSETTE': '卡座',
    'PRIVATE_ROOM': '包房',
    'DINING_TABLE': '餐桌'
};

const STATUS_LIST = [{ name: "正在执行", value: 'DOING' }, { name: '挂起', value: 'SUSPEND' }, {
    name: '完成',
    value: 'DONE'
}, {
    name: '取消',
    value: 'CANCEL'
},
    {
        name: '预约',
        value: 'BESPEAK'
    }
];

class OrderList extends React.Component {
    // 构造
    constructor (props) {
        super(props);
        // 初始状态
        this.state = {
            data: [],
            currentPage: 1,
            total: 0,
            payBillShow: false,
            addShow: false,
            addOrderShow: false,
            addRemarkShow: false,
            loading: {},
            expandTable: {},
            optionsData: [],
            waiterData: [],
            updateLoading: false,
            // 新增菜品布局数组
            foodLayout: [],
            // 订单备注
            remarkVal: '',
            remarkOrderId: ''
        };
        this.searchData = { pageSize: DEFAULT_PAGE_SIZE };
        this.page = 1;
        this.payBillData = { cost: '' };
    }

    componentDidMount () {
        // To disabled submit button at the beginning.
        this.submit();
        this.requestMenu();
    }

    handleExpand = (record) => {
        this.setState({
            expandTable: { ...record }
        })
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.submit();
    };

    handleFilterTable = (value, selectedOptions) => {
        console.log(value, selectedOptions)
    };

    submit () {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                let { time, ...data } = values;
                let payStartTime, payEndTime;
                if (Array.isArray(time) && time.length === 2) {
                    payStartTime = time[0].format('YYYY-MM-DD');
                    payEndTime = time[1].format('YYYY-MM-DD');
                }
                data = {
                    ...data,
                    payStartTime,
                    payEndTime
                }
                let tableOrRoom = values.tableOrRoom ? values.tableOrRoom[1] : '';
                this.searchData = { ...this.searchData, ...data, tableOrRoom };
                this._requestData(1)
                    .then(() => {
                        const {waiterData, optionsData} = this.state;
                        if (!waiterData.length) {
                            this.requestWaiterData();
                        }
                        if (!optionsData.length) {
                            this.requestTableData();
                        }
                    })
            }
        });
    }

    _requestData = (page) => {
        return new Promise((resolve, reject) => {
            const { auth: auth = { data: {} } } = this.props;
            if (auth.data && auth.data.restaurant) {
                get('/order/listItem', {
                    ...this.searchData,
                    restaurantID: auth.data.restaurant,
                    page: page
                }).then(data => {
                    console.log(' _requestData', data);
                    const dataSource = data.data.map(item => {
                        return { ...item, key: item.id };
                    });
                    this.setState({ data: dataSource, total: data.total });
                    resolve();
                });
            } else {
                console.log(this.props);
                this.props.router.push('/login');
                reject();
            }
        })
    };

    requstBillData = (id) => {
        return get('/order/item/' + id);
    }

    // 加载餐桌数据
    requestTableData = () => {
        // if (this.state.optionsData.length > 0) return
        const { auth: auth = { data: {} } } = this.props;
        if (auth.data && auth.data.restaurant) {
            get('/restaurant/listTableOrRoom', { restaurantID: auth.data.restaurant, type: '' })
                .then((res) => {
                    let optionsData = [];
                    res.forEach((tableData) => {
                        let hasType = false
                        let typeIndex = 0;
                        let type = tableData.type;
                        let children = { label: tableData.orderNum, value: tableData.orderNum, data: tableData };
                        optionsData.forEach((option, index) => {
                            if (option.value === type) {
                                hasType = true;
                                typeIndex = index;
                            }
                        })
                        if (!hasType) {
                            optionsData.push({
                                label: typeMap[type],
                                value: type,
                                children: [children]
                            });
                        } else {
                            optionsData[typeIndex].children.push(children);
                        }
                    });
                    this.setState({ optionsData })
                    // console.log(optionsData)
                }, (err) => {
                    console.log(err);
                })
        }
    }

    requestWaiterData = () => {
        const { auth: auth = { data: {} } } = this.props;
        return get('/restaurant/listWaiter', { restaurantID: auth.data.restaurant, page: 1, pageSize: 300 })
            .then((res) => {
                const { data } = res;
                let waiterData = [{
                    label: '服务员',
                    children: []
                }];
                data.forEach(item => {
                    waiterData[0].children.push({
                        value: item.id,
                        label: item.name
                    })
                })
                this.setState({ waiterData })
            }, (err) => {
                console.error('request waiter: ' + err);
            })
    }

    requstByAddFood = (data) => {
        let { tableData } = this.state;
        this._requestData(this.state.currentPage)
        /*.then(() => {
         if (data) {
         tableData = this.state.data.find(v => v.id === data.id);
         // console.log(tableData)
         this.setState({tableData});
         }
         })*/
    }

    requestMenu = () => {
        const { auth: { data: { restaurant: restaurantID } } } = this.props;
        get('/restaurant/listMenus/' + restaurantID)
            .then((res) => {
                this.requestAllFood(res.list, restaurantID);
            }, (err) => {
                console.log(err);
            })
    }

    // 请求菜单下所有菜品
    requestAllFood = (menuList, restaurantID) => {
        let requests = [];
        let menuData = [];
        menuList.forEach((menu, index) => {
            requests.push(get('/restaurant/listFood', {
                restaurantID,
                page: 1,
                pageSize: 300,
                menuID: menu.id,
                status: 'ENABLE'
            }))
            menuData.push({
                menuId: menu.id,
                menuName: menu.name,
                foods: []
            })
        });
        axios.all(requests)
            .then(axios.spread((...args) => {
                args.forEach((foods, index) => {
                    menuData[index].foods = foods.data;
                });
                this.setFoodLayout(menuData);
            }))
    }

    // 设置菜品布局对象
    setFoodLayout = (menuData) => {
        // let {foodLayout} = this.state;
        let foodLayout = [];

        // console.log(menuData)
        /* menuData.sort((a, b) => {
             return b.foods.length - a.foods.length;
         })*/
        menuData.forEach(foodData => {
            if (foodData.foods.length > 0) {
                foodLayout.push(foodData);
            }
        })
        this.setState({ foodLayout });
    }


    // 添加新订单
    handleAddOrder = () => {
        this.setState({ addOrderShow: true });
    }

    // 取消订单
    handleCancelOrder = (record) => {
        request({ url: '/order/item/' + record.id, method: 'delete' }).then((res) => {
            this._requestData(this.state.currentPage);
            message.success('订单取消成功！')
        })
    };


    // 取消单个菜品
    handleCancelFood = (record, expandData) => {
        const { tableData } = this.state;
        // 如果是缓存 添加的菜品 直接删除
        if (record.cache) {
            expandData.items = expandData.items.filter(item => item.uid !== record.uid);
        } else {
            // 判断是否取消菜品
            if (typeof(record.originStatus) === 'undefined') record.originStatus = record.status;
            record.statusChange = record.originStatus !== 'CANCEL';
            record.status = "CANCEL";
        }
        this.setState({ tableData });
    };

    // 添加订单备注
    handleAddRemark = (record) => {
        let remarkVal = record.actionExtra || '';
        this.remarkVal = remarkVal;
        this.setState({ addRemarkShow: true, remarkOrderId: record.id, remarkVal })
    }

    // 提交订单备注
    handleSubmitRemark = () => {
        let { remarkOrderId: id, remarkVal: content, data } = this.state;
        request({
            url: '/order/updateOrderActionExtra', method: 'post', params: {
                id,
                content
            }
        }).then((res) => {
            data = data.map(record => {
                if (record.id === id) record.actionExtra = content;
                return record;
            });
            this.setState({ addRemarkShow: false, remarkVal: '', data });
            // this._requestData(this.state.currentPage);
        }, (err) => {
            message.error('提交失败')
        });
        console.log(this.state.remarkVal)
    };

    //更新订单信息
    _updateOrderItem = data => {
        return new Promise((resolve, reject) => {
            if (data && Array.isArray(data.items)) {
                this.setState({ updateLoading: true });
                let { tableData } = this.state;
                let items = data.items.filter(v => v.statusChange || v.isChange || v.cache);
                /** 删除套餐对象下的 多余 items **/
                items = items.map(item => {
                    if (item.items) delete item.items;
                    return item;
                });
                data = { ...data, items };
                request({ url: '/order/item', method: 'post', body: data }).then(res => {
                    this.requstByAddFood(res);
                    this.setState({ updateLoading: false });
                    resolve();
                }, (err) => {
                    reject(err);
                });
                console.log(' _updateOrderItem    ', data);
            } else {
                reject()
            }
        })

    };

    // 打印订单
    printReq = (id) => {
        request({ url: '/order/printOrder/' + id, method: 'post', });
    };

    _printFinishOrder = param => {
        request({ url: '/order/printFinishOrder/', method: 'post', params: param });
    };

    /*挂起订单*/
    _suspendOrder = id => {
        request({ url: '/order/suspend/' + id, method: 'post' });
    };

    render () {
        const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
        const columns = [
                {
                    title: 'ID',
                    dataIndex: 'id',
                    key: 'id',
                    render: (text) => {
                        return ('0000' + text).slice(-4);
                    }
                }, {
                    title: '桌号',
                    dataIndex: 'tableOrRoom',
                    key: 'tableOrRoom'
                },
                {
                    title: '服务员',
                    dataIndex: 'waiterID',
                    key: 'waiterID',
                    render: waiterID => {
                        const { waiterData } = this.state;
                        if (!waiterData.length) return;
                        const waiter = waiterData[0].children.filter(item => {
                            return item.value === waiterID
                        })[0]
                        return waiter ? waiter.label : ''
                    }
                },
                {
                    title: '买单',
                    key: 'payBill',
                    width: 120,
                    render: (text, data) => {
                        return <div className="btn-gourp">
                            {data.status !== 'DONE' && <Button
                                disabled={/^DONE$|^CANCEL$/.test(data.status)}
                                loading={this.state.loading[data.id]}
                                onClick={e => {
                                    // console.log('OrderList data    ', data);
                                    let timer = setTimeout(() => {
                                        this.setState({ loading: { [data.id]: true } });
                                    }, 200)
                                    this.requstBillData(data.id)
                                        .then((res) => {
                                            let { paybill } = this.refs;
                                            if (paybill) {
                                                paybill.resetFields();
                                            }
                                            this.payBillData = res;
                                            clearInterval(timer);
                                            this.setState({ payBillShow: true, loading: {} });
                                        })
                                }
                                }>买单</Button>
                            }
                        </div>
                    }
                }, {
                    title: '总价（¥）',
                    dataIndex: 'cost',
                    key: 'cost'
                }, {
                    title: '折后价（¥）',
                    dataIndex: 'discountCost',
                    key: 'discountCost'
                }, {
                    title: '支付类型', dataIndex: 'payType', render: (text) => text && text.alias
                },
                {
                    title: '收入（¥）',
                    dataIndex: 'income',
                    key: 'income'
                }
                ,
                {
                    title: '找零（¥）',
                    dataIndex: 'change',
                    key: 'change'
                }
                ,
                {
                    title: '状态',
                    dataIndex: 'status',
                    render: (text) => STATUS_LIST.find(v => v.value === text).name
                }
                ,
                {
                    title: '预约时间',
                    dataIndex: 'bespeakTime',
                    key: 'bespeakTime',
                    width: 90,
                    render: (text) => {
                        return <span>{moment(text).format(FORMAT_DATE)}</span>
                    }
                },
                {
                    title: '创建时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                    width: 90,
                    render: (text) => {
                        return moment(text).format(FORMAT_DATE);
                    }
                },
                // { title: '支付时间', dataIndex: 'payTime' },
                {
                    title: '操作',
                    width: 220,
                    render: (text, record, index) => {
                        const id = record.id;
                        return (
                            <div className="btn-group">
                                <Popconfirm
                                    title="确定打印该订单?"
                                    onConfirm={() => this.printReq(id)}
                                    okText="确定"
                                    cancelText="取消"
                                >
                                    <Button>补打订单</Button>
                                </Popconfirm>
                                <Popconfirm
                                    title="是否打印操作备注？"
                                    onConfirm={() => this._printFinishOrder({ id, printAction: true })}
                                    onCancel={() => this._printFinishOrder({ id, printAction: false })}
                                    okText="是"
                                    cancelText="否"
                                >
                                    <Button>打印账单</Button>
                                </Popconfirm>
                                {
                                    !/^DONE$|^CANCEL$/.test(record.status) && <Popconfirm
                                        title="确定取消该订单?"
                                        onConfirm={() => this.handleCancelOrder(record)}
                                        okText="确定"
                                        cancelText="取消"
                                    >
                                        <Button type="dashed" className="cancel-btn">取消</Button>
                                    </Popconfirm>
                                }
                                {record.status === 'DOING' ? <Popconfirm title='确认挂起该订单？'
                                                                         onConfirm={() => this._suspendOrder(id)}
                                                                         okText="是"
                                                                         cancelText="否"
                                ><Button type="dashed" className="hang-btn">挂起</Button></Popconfirm> : null}
                            </div>
                        )
                    }
                }
                ,
                {
                    title: '操作备注',
                    dataIndex: 'actionExtra',
                    render: (text) => text && text.substring(0, 6) + '...'
                }
            ]
        ;

        return (
            <div className="content-container">
                <Form layout="inline" onSubmit={this.handleSubmit}>
                    <FormItem
                        label={'订单状态'}
                    >
                        {getFieldDecorator('status', {
                            rules: [{ required: false, message: '选择订单类型' }],
                            initialValue: 'DOING'
                        })(
                            <Select placeholder={'选择类型'} style={{ width: 120 }} allowClear>
                                {STATUS_LIST.map((item, index) => <Option value={item.value}
                                                                          key={item.value}> {item.name}</Option>)}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                    >
                        {getFieldDecorator('time', {})(
                            <RangePicker/>
                        )}
                    </FormItem>
                    <FormItem
                        label={'餐桌编号'}
                    >
                        {getFieldDecorator('tableOrRoom', {})(
                            <Cascader
                                options={this.state.optionsData}
                                expandTrigger="hover"
                                placeholder="请选择"
                                onChange={this.handleFilterTable}
                            />
                        )}
                    </FormItem>
                    <FormItem>
                        <Button
                            type="primary"
                            htmlType="submit"
                        >
                            搜索
                        </Button>
                    </FormItem>
                    <FormItem>
                        <Button
                            type="primary"
                            onClick={this.handleAddOrder}
                        >
                            添加订单
                        </Button>
                    </FormItem>
                    <FormItem>
                        <Button
                            icon="reload"
                            type="primary"
                            onClick={() => {
                                this._requestData(this.state.currentPage);
                                this.requestMenu();
                            }}
                        >
                        </Button>
                    </FormItem>
                </Form>
                <div className="space-bar"></div>
                <Table columns={columns} dataSource={this.state.data}
                       onExpand={(expanded, record) => this.handleExpand(record)}
                       expandedRowRender={record => {
                           return (
                               <ExpandTable
                                   record={record}
                                   _updateOrderItem={this._updateOrderItem}
                                   updateLoading={this.state.updateLoading}
                                   handleCancelFood={this.handleCancelFood}
                                   handleAddRemark={this.handleAddRemark}
                                   handleAddFood={() => {
                                       this.setState({ tableData: record, addShow: true });

                                       const { addfood } = this.refs;
                                       if (addfood) {
                                           addfood.resetFields();
                                           setTimeout(() => {
                                               let foodNum = document.querySelectorAll(".food-num");
                                               for (let i = 0; i < foodNum.length; i++) {
                                                   {/*console.log(foodNum[i].querySelector('input'))*/
                                                   }
                                                   foodNum[i].value = 1;
                                               }
                                           }, 0)
                                       }
                                   }}
                               />
                           )

                       }
                       }
                       pagination={
                           {
                               total: this.state.total,
                               defaultPageSize: DEFAULT_PAGE_SIZE,
                               current: this.state.currentPage,
                               onChange: (current) => {
                                   this.setState({ currentPage: current });
                                   this._requestData(current);
                               }
                           }
                       }/>
                <Modal visible={this.state.payBillShow} maskClosable={false} footer={null} onCancel={e => {
                    this.payBillData = {};
                    this.props.updateMember({})
                    this.setState({ payBillShow: false });
                }}>
                    <PayBill ref="paybill"
                             data={this.payBillData}
                             memberInfo={this.props.memberInfo}
                             updateMember={this.props.updateMember}
                             success={() => {
                                 this.setState({ payBillShow: false });
                                 this._requestData(this.page);
                                 this.props.updateMember({}, 'memberInfo')
                             }}
                    />
                </Modal>
                <Modal
                    visible={this.state.addShow}
                    maskClosable={false}
                    footer={null}
                    width={'1160px'}
                    onCancel={e => {
                        this.setState({ addShow: false });
                    }}>
                    <AddFood ref="addfood"
                             data={this.state.tableData}
                             foodLayout={this.state.foodLayout}
                             submit={data => {
                                 const tableData = this.state.tableData;
                                 if (data) {
                                     data.forEach((dataItem) => {
                                         tableData.items.push(dataItem);
                                     })
                                 }
                                 ;
                                 this.setState({ tableData, addShow: false });
                             }}
                    />
                </Modal>
                <Modal visible={this.state.addOrderShow} footer={null} onCancel={e => {
                    this.setState({ addOrderShow: false });
                }}>
                    <AddOrder
                        {...this.props}
                        requstByAdd={this.requstByAddFood}
                        optionsData={this.state.optionsData}
                        waiterData={this.state.waiterData}
                        afterSubmit={() => {
                            this.setState({ addOrderShow: false })
                        }}
                    />
                </Modal>
                <Modal
                    title="添加订单备注"
                    visible={this.state.addRemarkShow}
                    onOk={this.handleSubmitRemark}
                    onCancel={e => {
                        this.setState({ addRemarkShow: false });
                    }}
                >
                    <TextArea rows={4} placeholder="备注"
                              value={this.state.remarkVal}
                              onChange={(e) => {
                                  const old = this.remarkVal;
                                  const newContent = e.target.value;
                                  this.setState({ remarkVal: newContent });
                              }}
                    />
                </Modal>
            </div>
        );
    }
}

const mapStateToPorps = state => {
    const { auth } = state.httpData;
    const { memberInfo } = state;
    return { auth, memberInfo };
};

const mapDispatchToProps = dispatch => ({
    fetchData: bindActionCreators(fetchData, dispatch),
    receiveData: bindActionCreators(receiveData, dispatch),
    updateMember: (...args) => dispatch(updateMember(...args))
});


export default connect(mapStateToPorps, mapDispatchToProps)(Form.create()(OrderList));